<?php
declare(strict_types=1);

namespace App\AdminApi\Module\System\Traits;

use App\AdminApi\Module\System\Service\ConfigureService;
use App\Sys;
use Zms\AdminElementPlus\FormCreate\Form;
use Zms\Exception\AppException;
use Zms\Exception\ValidateException;
use Zms\Unit\Str;
use Zms\Validate\Validate;

/**
 * 配置混入
 */
trait ConfigureTraits
{
    /**
     * 获取表单配置
     * @param string $key
     * @param string $api
     * @return array
     * @throws AppException
     */
    public function getConfigureForm(string $key, string $api = '', string $title = '配置修改', string $width = '100px'): array
    {
        $formName = Str::doubleToHump('get-' . ucfirst($key) . '-form-rule', '-');
        if (!in_array($formName, get_class_methods($this))) {
            throw new AppException("尚未配置相关表单");
        }
        return Form::create($title, $api)
            ->labelWidth($width)
            ->setRules(array_reverse(call_user_func([$this, $formName], Sys::conf($key, []))))
            ->setOptionFormInline(true)
            ->toArray();
    }


    /**
     * 写入表单配置
     * @param string $key
     * @param array $value
     * @return void
     * @throws ValidateException|AppException
     */
    public function setConfigure(string $key, array $value): void
    {
        $formName = Str::doubleToHump('get-' . ucfirst($key) . '-validate-rule', '-');
        if (in_array($formName, get_class_methods($this))) {
            $result = call_user_func([$this, $formName]);//返回['rule'=>[],'label'=>[]]
            $validate = (new Validate())->setData($value)->setRules($result['rule'])->setLabels($result['label'])->validate();
            if ($validate->isFail()) {
                throw new ValidateException($validate->firstError());
            }
            $value = $validate->getSafeData();
        }
        if (!Sys::container(ConfigureService::class)->writeConfiguration($key, $value)) {
            throw new AppException("配置保存失败");
        }
    }
}